<?php

namespace app\api\controller;


use addons\epay\library\Service;
use app\admin\model\CardOrder;
use app\admin\model\Crontab;

use app\common\controller\Api;
use think\Exception;


/**
 * 接口
 */
class Block extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //会员卡支付回调
    public function cardnotifyx()
    {
        $paytype = "wechat";
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            return;
        }
        $data = $pay->verify();
        \think\Log::record($data);

        try {
            $out_trade_no = $data['out_trade_no'];
            $order_no = explode("_",$out_trade_no);
            //$order_no[0] = '202503141627211802';
            //$data['transaction_id'] = 4200002686202503140181829855;
            $orderModel = new CardOrder();
            $orderInfo = $orderModel->where(['order_no'=>$order_no[0],'pay_status'=>0])->find();

            if($orderInfo){
                if ($orderInfo['type']==1){
                    $time = 30*86400;
                } elseif ($orderInfo['type']==2){
                    $time = 180*86400;
                } else {
                    $time = 365*86400;
                }

                $orderInfo->save(['pay_status'=>1,'transaction_id'=>$data['transaction_id'],'pay_time'=>time(),'expire_time'=>time()+$time]);

                $user = \app\admin\model\User::get($orderInfo['user_id']);

                $user->card_expiry_time = time()+$time;
                $user->vip = 1;
                $endtime = $user->card_expiry_time;
                $res = $user->save();

                $title = '用户会员到期,用户id:'.$orderInfo['user_id'];

                $cron_detail = Crontab::get(['status'=>'normal','title'=>$title]);
                if ($cron_detail){
                    $cron_detail->status = 'hidden';
                    $cron_detail->save();
                }

                $cron = new Crontab();
                $cron->setAttr('type','url');
                $cron->title = $title;
                $cron->content = request()->domain().'/api/block/cardexpiry?user_id='.$orderInfo['user_id'];
                $cron->schedule = schedule($endtime);
                $cron->maximums = 1;
                $cron->begintime = $endtime-60;
                $cron->endtime = $endtime;
                $cron->status = 'normal';
                $cron->save();

            }
        } catch (Exception $e) {
            \think\Log::record($e->getMessage());
        }
        echo $pay->success();
    }

    //会员卡到期
    public function cardexpiry($user_id)
    {
        $user = \app\admin\model\User::get($user_id);
        $user->vip = 0;
        $user->save();
    }

}